﻿using DataRecv.models.recever;
using DataRecv.models.sdk.HKSDK;
using MCInsertDb;
using SHANGBN1.DAL;
using SHANGBN1.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace SHANGBN1
{
    public partial class Form1 : Form
    {
        int Port = 8000;
        //state.Ping = false;
        int LoginID = -1;
        int Channel = -2;
        bool IsOpen = false;
        int PlayHandle = -2;
        int AlarmHandle = -1;
        string ipaddress = null;
        string username = null;
        string password = null;
        public bool m_Init;
        public bool m_CameraCallBackSet;
        public int m_HostCallBackSet;
        public Timer m_InitTimer;
        public CHCNetSDK.MSGCallBack m_CameraCallBack;
        public CHCNetSDK.MSGCallBack m_HostCallBack;

        public Form1()
        {
            InitializeComponent();
            Port = 8000;
            //state.Ping = false;
            LoginID = -1;
            Channel = -2;
            IsOpen = false;
            PlayHandle = -2;
            AlarmHandle = -1;
            m_struDeviceInfo = new CHCNetSDK.NET_DVR_DEVICEINFO_V30();
            m_SetAlarmParam = new CHCNetSDK.NET_DVR_SETUPALARM_PARAM();
            m_SetAlarmParam.dwSize = (uint)Marshal.SizeOf(m_SetAlarmParam);//20
            try
            {
                m_SetAlarmParam.byLevel = 0;//布防优先级：0- 一等级（高），1- 二等级（中），2- 三等级（低，保留）
            }
            catch { m_SetAlarmParam.byLevel = 0; }
            //m_SetAlarmParam.byLevel = (deviceview.deviceparam.bz.Contains("二级布防") ? (byte)1 : (byte)0);//布防优先级：0- 一等级（高），1- 二等级（中），2- 三等级（低，保留）
            m_SetAlarmParam.byAlarmInfoType = 1;//上传报警信息类型（智能交通摄像机支持）：0- 老报警信息（NET_DVR_PLATE_RESULT），1- 新报警信息(NET_ITS_PLATE_RESULT)

        }

        private CHCNetSDK.NET_DVR_DEVICEINFO_V30 m_struDeviceInfo;
        private CHCNetSDK.NET_DVR_SETUPALARM_PARAM m_SetAlarmParam;

        /// <summary>
        /// HK9151系列
        /// </summary>


        public void Init(object obj)
        {
            try
            {


                if (AlarmHandle >= 0)//如果是网络之前是连接的，需要撤防
                {
                    CHCNetSDK.NET_DVR_CloseAlarmChan_V30(AlarmHandle);
                    AlarmHandle = -1;
                }
                if (LoginID >= 0)//如果是网络之前是连接的，需要注销
                {
                    CHCNetSDK.NET_DVR_Logout_V30(LoginID);
                    LoginID = -1;
                }



                //注册设备
                if (LoginID < 0)
                {
                    LoginID = CHCNetSDK.NET_DVR_Login_V30(ipaddress, Port, username, password, ref m_struDeviceInfo);
                    if (LoginID < 0)
                    {
                        //LogTool.log.Info("HK9151摄像机---" + deviceview.deviceparam.ip + "---注册失败");
                        return;
                    }
                }

                //启用布防
                if (AlarmHandle < 0)
                {
                    //m_AlarmHandle = CHCNetSDK.NET_DVR_SetupAlarmChan_V30(m_UserID);
                    AlarmHandle = CHCNetSDK.NET_DVR_SetupAlarmChan_V41(LoginID, ref m_SetAlarmParam);
                    if (AlarmHandle < 0)
                    {
                        //LogTool.log.Info("HK9151摄像机---" + deviceview.deviceparam.ip + "---布防失败,code=" + CHCNetSDK.NET_DVR_GetLastError().ToString());

                        if (m_SetAlarmParam.byLevel == 0)
                        {
                            if (CHCNetSDK.NET_DVR_RebootDVR(LoginID) == true)
                            {
                                //LogTool.log.Info("HK9151摄像机---" + deviceview.deviceparam.ip + "---重启");
                            }
                        }
                    }
                    else
                    {
                        //LogTool.log.Info("HK9151摄像机---" + deviceview.deviceparam.ip + "---注册布防成功");
                    }
                }
            }
            catch (Exception er)
            {
                //LogTool.log.Info("HK9151.Init()---" + deviceview.deviceparam.ip + "---" + er.Message);
            }
        }

        private void InitTimerCallbackFunc(object obj)
        {
            try
            {
                if (m_Init == false)
                {
                    m_Init = CHCNetSDK.NET_DVR_Init();//初始化SDK
                    CHCNetSDK.NET_DVR_SetConnectTime(2000, 1);    //2.设置连接超时时间ms
                    CHCNetSDK.NET_DVR_SetReconnect(10000, 1);  //3.设置重连间隔ms
                }

                if (m_Init == true)
                {

                    m_CameraCallBack = new CHCNetSDK.MSGCallBack(HKCameraFunc);
                    m_CameraCallBackSet = CHCNetSDK.NET_DVR_SetDVRMessageCallBack_V30(m_CameraCallBack, IntPtr.Zero);
                    //LogTool.log.Info("HK布防回调设置" + (m_CameraCallBackSet ? "成功" : "失败"));

                }
            }
            catch (Exception er)
            {
                //LogTool.log.Info("Recever_HK.InitTimerCallbackFunc()" + er.Message);
            }
        }

        //“海康摄像机”回调函数
        private void HKCameraFunc(int lCommand, ref CHCNetSDK.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
        {
            try
            {

                //新报警信息类型
                if (lCommand == 0x3050)
                {
                    //G.N++;
                    Recever_Bag bag = new Recever_Bag();
                    bag.ip = pAlarmer.sDeviceIP;
                    //bag.id = G.N;
                    bag.type = "HKA";
                    //if (LogTool.gDebugEnable) LogTool.log.Info("1A " + bag.Txt());
                    bag.NET_ITS_PLATE_RESULT = (CHCNetSDK.NET_ITS_PLATE_RESULT)Marshal.PtrToStructure(pAlarmInfo, typeof(CHCNetSDK.NET_ITS_PLATE_RESULT));
                    //ThreadPool.QueueUserWorkItem(new WaitCallback(HKCameraAThreadFunc), bag);
                    HKCameraAThreadFunc(bag);
                }

                //老报警信息类型
                if (lCommand == 0x2800)
                {
                    //G.N++;
                    Recever_Bag bag = new Recever_Bag();
                    bag.ip = pAlarmer.sDeviceIP;
                    //bag.id = G.N;
                    bag.type = "HKB";
                    //if (LogTool.gDebugEnable) LogTool.log.Info("1B " + bag.Txt());
                    bag.NET_DVR_PLATE_RESULT = (CHCNetSDK.NET_DVR_PLATE_RESULT)Marshal.PtrToStructure(pAlarmInfo, typeof(CHCNetSDK.NET_DVR_PLATE_RESULT));
                    //ThreadPool.QueueUserWorkItem(new WaitCallback(HKCameraBThreadFunc), bag);
                    //HKCameraBThreadFunc(bag);
                }
                
            }
            catch (Exception er)
            {
                //LogTool.log.Info("HKCameraFunc() N=" + G.N.ToString() + " HKcam ip=" + pAlarmer.sDeviceIP + er.Message);
                if (er.Message.Contains("OutOfMemoryException"))
                {
                    GC.Collect();
                }

            }
        }

       

        private void HKCameraAThreadFunc(object obj)
        {
            Recever_Bag bag = (Recever_Bag)obj;

            try
            {

                CHCNetSDK.NET_ITS_PLATE_RESULT Result = bag.NET_ITS_PLATE_RESULT;

                #region 1数据转换
                


                switch (Result.wIllegalType)
                {
                    case 1349://机动车行驶超过规定时速50%以下
                        Result.struVehicleInfo.byIllegalType = 1;//低速;
                        break;
                    case 1632://机动车行驶超过规定时速50%
                        Result.struVehicleInfo.byIllegalType = 2;//超速;
                        break;
                    case 1301:
                        Result.struVehicleInfo.byIllegalType = 3;//逆行;
                        break;
                    case 1302:
                    case 1625:
                        Result.struVehicleInfo.byIllegalType = 4;//闯红灯;
                        break;
                    case 13451:
                        Result.struVehicleInfo.byIllegalType = 5;//压线;
                        break;
                    case 1208:
                        Result.struVehicleInfo.byIllegalType = 6;//不按导线行驶;
                        break;
                    case 1344:
                        Result.struVehicleInfo.byIllegalType = 9;//违章变道;
                        break;
                    case 1211:
                    case 4613:
                        Result.struVehicleInfo.byIllegalType = 12;//路口停车,违法停车;
                        break;
                    default:
                        break;
                }
                //LogTool.log.Info("wIllegalType=" + Result.wIllegalType + " byIllegalType=" + Result.struVehicleInfo.byIllegalType);

                string P7 = "2";//采集方式(必须)1:闯红灯自动记录设备2:公路车辆智能监控设备3:测速设备4:闭路电视5:移动摄像6:数码相机7:区间测速8:卫星定位装置9:其它电子设备11:群众举报
                switch (Result.struVehicleInfo.byIllegalType)
                {
                    case 0:
                        P7 = "2";
                        break;
                    case 1:
                        P7 = "3";
                        break;
                    case 2:
                        P7 = "3";
                        break;
                    case 3:
                    case 4:
                    case 5:
                    case 6:
                    case 7:
                    case 8:
                    case 9:
                    case 10:
                    case 11:
                    case 12:
                        P7 = "1";
                        break;
                    default:
                        break;
                }
                bag.bz = Result.struVehicleInfo.byIllegalType.ToString();
                //if (LogTool.gDebugEnable) LogTool.log.Info("2A " + bag.Txt());
                //DeviceView thisview = (DeviceView)G.Views[bag.ip];

                string P18 = Encoding.Default.GetString(Result.struPicInfo[0].byAbsTime).Trim('\0');
                string yyyy = P18.Substring(0, 4);
                string MM = P18.Substring(4, 2);
                string dd = P18.Substring(6, 2);
                string HH = P18.Substring(8, 2);
                string mm = P18.Substring(10, 2);
                string ss = P18.Substring(12, 2);
                string fff = P18.Substring(14, 3);
                string P19 = yyyy + "-" + MM + "-" + dd + " " + HH + ":" + mm + ":" + ss;


                string plateWithColor = Result.struPlateInfo.sLicense.ToString();
                string P21 = "";
                string P22 = "";
                string P23 = "";

                if (plateWithColor.Contains("蓝"))
                {
                    P22 = "蓝";
                    P23 = plateWithColor.Replace("蓝", "");
                }
                else if (plateWithColor.Contains("黄"))
                {
                    P22 = "黄";
                    P23 = plateWithColor.Replace("黄", "");
                }
                else if (plateWithColor.Contains("白"))
                {
                    P22 = "白";
                    P23 = plateWithColor.Replace("白", "");
                }
                else if (plateWithColor.Contains("黑"))
                {
                    P22 = "黑";
                    P23 = plateWithColor.Replace("黑", "");
                }
                else if (plateWithColor.Contains("无"))
                {
                    P22 = "";
                    P23 = "";
                }
                else
                {
                    P22 = "";
                    P23 = plateWithColor;
                }

                if (P23.Contains("挂"))
                {
                    P21 = "15";
                    P23 = P23.Replace("挂", "");
                }
                else if (P23.Contains("学"))
                {
                    P21 = "16";
                    P23 = P23.Replace("学", "");
                }
                else if (P23.Contains("警"))
                {
                    P21 = "23";
                    P23 = P23.Replace("警", "");
                }
                else if (P22.Contains("蓝"))
                {
                    P21 = "02";
                }
                else if (P22.Contains("黄"))
                {
                    P21 = "01";
                }
                else
                {
                    P21 = "";
                }


                //车辆类型：0- 未知，1- 客车，2- 货车，3- 轿车，4- 面包车，5- 小货车
                //0- 未知，1- 客车(大型)，2- 货车(大型)，3- 轿车(小型)，4- 面包车，5- 小货车，6- 行人，7- 二轮车，8- 三轮车，9- SUV/MPV，10- 中型客车 
                string P44 = Result.byVehicleType.ToString();

                HPHM_textBox.Text = P23;
                #endregion


            }
            catch (Exception er)
            {
                //LogTool.log.Info("HKCameraAThreadFunc() " + bag.Txt() + er.Message);
                if (er.Message.Contains("OutOfMemoryException"))
                {
                    GC.Collect();
                }
            }
        }


        private void in_button_Click(object sender, EventArgs e)
        {

            //MessageBox.Show("入库成功，号牌=：" + HPHM_textBox.Text + "入库时间=：" + DateTime.Now + "仓库号=：3" );
            if (HPHM_textBox.Text == "")
            {
                MessageBox.Show("车牌号输入错误", "信息提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                return;
            }
            if (HPHM_textBox.Text.Contains("O") || HPHM_textBox.Text.Contains("I"))
            {
                MessageBox.Show("车牌号不能输入字母O或字母I", "信息提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                return;
            }
            HPXX hpxx = new HPXX();
            hpxx.Hphm = label2.Text + HPHM_textBox.Text;
            hpxx.Rksj = DateTime.Now;
            string CKReturn = null;
            try
            {
                CKReturn = new CKXXDAL().GetById();
                if (CKReturn == null)
                {
                    LogHelper.WriteLog(typeof(Form1), "仓库全满，返回空值");
                    return;
                }
                else
                {
                    hpxx.Ckh = CKReturn;
                }
            }
            catch (System.Exception ex)
            {
                LogHelper.WriteLog(typeof(Form1), ex, ex.Message + "CKReturnnew出错");
            }

            
            if (new HPXXDAL().GetByHphm(hpxx.Hphm)>=1)
            {
                MessageBox.Show("车牌号：  " + hpxx.Hphm + " 已存在", "信息提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                return;
            }
            if (new HPXXDAL().Insert(hpxx) > 0)
            {
                new CKXXDAL().UpdateAdd(Convert.ToInt32(CKReturn));
                LogHelper.WriteLog(typeof(Form1), "入库成功，号牌=：" + hpxx.Hphm + "入库时间=：" + hpxx.Rksj + "仓库号=：" + hpxx.Ckh);
                //MessageBox.Show("入库成功，号牌=：" + hpxx.Hphm + "入库时间=：" + hpxx.Rksj + "仓库号=：");

                try
                {
                    param form_param = new param(hpxx.Hphm, hpxx.Ckh,"入库成功！");
                    form_param.Owner = this;
                    form_param.ShowDialog();
                    form_param.Dispose();
                    HPHM_textBox.Text = "";
                    HPHM_textBox.Focus();
                }
                catch { }
            }
            else
            {
                LogHelper.WriteLog(typeof(Form1), "入库失败，号牌=：" + hpxx.Hphm + "入库时间=：" + hpxx.Rksj + "仓库号=：" + hpxx.Ckh);
            }

        }

        private void out_button_Click(object sender, EventArgs e)
        {
            if (HPHM_textBox.Text=="")
            {
                MessageBox.Show("车牌号输入错误", "信息提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                return;
            }
            if (HPHM_textBox.Text.Contains("O") || HPHM_textBox.Text.Contains("I"))
            {
                MessageBox.Show("车牌号不能输入字母O或字母I", "信息提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                return;
            }
            HPXX hpxx = new HPXX();
            hpxx.Hphm = label2.Text + HPHM_textBox.Text;
            hpxx.Cksj = DateTime.Now;
            if (new HPXXDAL().GetById(hpxx.Hphm)==null)
            {
                MessageBox.Show("无此号牌", "信息提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                return;
            }
            DataRow row= new HPXXDAL().GetById(hpxx.Hphm);

            hpxx.Ckh= row[1].ToString();
            hpxx.Lqzt = row[5].ToString();
            if (hpxx.Lqzt == "1")
            {
                try
                {
                    lingzou form_param = new lingzou();
                    form_param.Owner = this;
                    form_param.ShowDialog();
                    form_param.Dispose();
                    //HPHM_textBox.Text = "";
                    HPHM_textBox.Focus();
                    return;
                }
                catch { }
            }
            try
            {
                if (new HPXXDAL().Update(hpxx) > 0)
                {
                    new CKXXDAL().UpdateSub(Convert.ToInt32(hpxx.Ckh));

                    LogHelper.WriteLog(typeof(Form1), "出库成功，号牌=：" + hpxx.Hphm + "入库时间=：" + hpxx.Cksj + "仓库号=：" + hpxx.Ckh);
                    try
                    {
                        param form_param = new param(hpxx.Hphm, hpxx.Ckh, "出库成功！");
                        form_param.Owner = this;
                        form_param.ShowDialog();
                        form_param.Dispose();
                        HPHM_textBox.Text = "";
                        HPHM_textBox.Focus();
                    }
                    catch { }

                }
                else
                {
                    LogHelper.WriteLog(typeof(Form1), "出库失败，号牌=：" + hpxx.Hphm + "入库时间=：" + hpxx.Cksj + "仓库号=：" + hpxx.Ckh);
                }
            }
            catch (System.Exception ex)
            {
                LogHelper.WriteLog(typeof(Form1), ex, ex.Message + "出库失败");
            }
        }

        private void YIN_button_Click(object sender, EventArgs e)
        {
            if (YELLOW_HPHM_textBox.Text == "")
            {
                MessageBox.Show("车牌号输入错误", "信息提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                return;
            }
            if (YELLOW_HPHM_textBox.Text.Contains("O") || YELLOW_HPHM_textBox.Text.Contains("I"))
            {
                MessageBox.Show("车牌号不能输入字母O或字母I", "信息提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                return;
            }
            HPXX hpxx = new HPXX();
            hpxx.Hphm = label4.Text + YELLOW_HPHM_textBox.Text;
            hpxx.Rksj = DateTime.Now;
            string CKReturn = null;
            try
            {
                CKReturn = new CKXXDAL().GetById_YELLOW();
                if (CKReturn == null)
                {
                    LogHelper.WriteLog(typeof(Form1), "仓库全满，返回空值");
                    return;
                }
                else
                {
                    hpxx.Ckh = CKReturn;
                }
            }
            catch (System.Exception ex)
            {
                LogHelper.WriteLog(typeof(Form1), ex, ex.Message + "CKReturnnew出错");
            }


            if (new HPXXDAL().GetByHphm_YELLOW(hpxx.Hphm) >= 1)
            {
                MessageBox.Show("车牌号：  " + hpxx.Hphm + " 已存在", "信息提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                return;
            }
            if (new HPXXDAL().Insert_YELLOW(hpxx) > 0)
            {
                new CKXXDAL().UpdateAdd_YELLOW(Convert.ToInt32(CKReturn));
                LogHelper.WriteLog(typeof(Form1), "入库成功，号牌=：" + hpxx.Hphm + "入库时间=：" + hpxx.Rksj + "仓库号=：" + hpxx.Ckh);
                //MessageBox.Show("入库成功，号牌=：" + hpxx.Hphm + "入库时间=：" + hpxx.Rksj + "仓库号=：");

                try
                {
                    param form_param = new param(hpxx.Hphm, hpxx.Ckh, "入库成功！");
                    form_param.Owner = this;
                    form_param.ShowDialog();
                    form_param.Dispose();
                    YELLOW_HPHM_textBox.Text = "";
                    YELLOW_HPHM_textBox.Focus();
                }
                catch { }
            }
            else
            {
                LogHelper.WriteLog(typeof(Form1), "入库失败，号牌=：" + hpxx.Hphm + "入库时间=：" + hpxx.Rksj + "仓库号=：" + hpxx.Ckh);
            }
        }

        private void YOUT_button_Click(object sender, EventArgs e)
        {
            if (YELLOW_HPHM_textBox.Text == "")
            {
                MessageBox.Show("车牌号输入错误", "信息提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                return;
            }
            if (YELLOW_HPHM_textBox.Text.Contains("O") || YELLOW_HPHM_textBox.Text.Contains("I"))
            {
                MessageBox.Show("车牌号不能输入字母O或字母I", "信息提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                return;
            }
            HPXX hpxx = new HPXX();
            hpxx.Hphm = label4.Text + YELLOW_HPHM_textBox.Text;
            hpxx.Cksj = DateTime.Now;
            if (new HPXXDAL().GetById_YELLOW(hpxx.Hphm) == null)
            {
                MessageBox.Show("无此号牌", "信息提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                return;
            }
            DataRow row = new HPXXDAL().GetById_YELLOW(hpxx.Hphm);
            hpxx.Ckh = row[1].ToString();
            hpxx.Lqzt = row[5].ToString();
            if (hpxx.Lqzt == "1")
            {
                try
                {
                    lingzou form_param = new lingzou();
                    form_param.Owner = this;
                    form_param.ShowDialog();
                    form_param.Dispose();
                    //HPHM_textBox.Text = "";
                    YELLOW_HPHM_textBox.Focus();
                    return;
                }
                catch { }
            }
            try
            {
                if (new HPXXDAL().Update_YELLOW(hpxx) > 0)
                {
                    new CKXXDAL().UpdateSub_YELLOW(Convert.ToInt32(hpxx.Ckh));

                    LogHelper.WriteLog(typeof(Form1), "出库成功，号牌=：" + hpxx.Hphm + "入库时间=：" + hpxx.Cksj + "仓库号=：" + hpxx.Ckh);
                    try
                    {
                        param form_param = new param(hpxx.Hphm, hpxx.Ckh, "出库成功！");
                        form_param.Owner = this;
                        form_param.ShowDialog();
                        form_param.Dispose();
                        YELLOW_HPHM_textBox.Text = "";
                        YELLOW_HPHM_textBox.Focus();
                    }
                    catch { }

                }
                else
                {
                    LogHelper.WriteLog(typeof(Form1), "出库失败，号牌=：" + hpxx.Hphm + "入库时间=：" + hpxx.Cksj + "仓库号=：" + hpxx.Ckh);
                }
            }
            catch (System.Exception ex)
            {
                LogHelper.WriteLog(typeof(Form1), ex, ex.Message + "出库失败");
            }
        }
    }
}
